package com.lu.component.crypto.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;

import com.lu.component.crypto.annotations.FieldCrypto;
import com.lu.component.crypto.exception.CryptoException;
import com.lu.component.crypto.utils.CryptoUtil;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;

/**
 * 描述
 *
 * @author: zhanglu
 * @date: 2023/9/21 20:59
 * @modify: 修改人信息, 修改内容 2023/9/21 20:59
 */
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class DecryptInterceptor implements Interceptor {

    public Object intercept(Invocation invocation) {
        try {
            Object proceed = invocation.proceed();
            if (ObjectUtil.isNull(proceed)) {
                return proceed;
            }
            List<?> list = (List) proceed;
            for (Object obj : list) {
                Field[] fields = ReflectUtil.getFields(obj.getClass());
                for (Field field : fields) {
                    if ((field.getAnnotation(FieldCrypto.class)) != null) {
                        ReflectUtil.setFieldValue(obj, field, CryptoUtil.aesDecrypt((String) ReflectUtil.getFieldValue(obj, field)));
                    }
                }
            }
            return list;
        } catch (Exception e) {
            throw new CryptoException(e);
        }
    }

    public Object plugin(Object target) {
        return target instanceof ResultSetHandler ? Plugin.wrap(target, this) : target;
    }

}
